//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using CommunityServer.Components;

namespace CommunityServer.Files.Components
{
	/// <summary>
	/// Handler for file gallery RSS feeds
	/// </summary>
	public class FileGalleryRssHandler : BaseFileGallerySyndicationHandler
	{
		protected bool SortByDownloads = false;
		protected string[] Tags = null;
		protected bool AndTags = false;
		
		public FileGalleryRssHandler() { }

		protected override string CacheKey
		{
			get
			{
				string key;
					key = string.Format("Folder:{0}:Rss", CurrentSection.SectionID);
				
				if(SortByDownloads)
					key = string.Concat(key, ":Downloads");

				if (this.Tags != null)
					key = string.Concat(key, string.Format(":Tags{0}:AndTags:{1}", string.Join(",", Tags), AndTags));

				return key;
			}
		}

		protected override void ProcessFeed()
		{
			SortByDownloads = Globals.SafeBool(Context.Request.QueryString["Downloads"], false);

			CSContext csContext = CSContext.Current;
			if(csContext.Tags != null)
			{
				this.Tags = csContext.Tags;
				if (Context.Request.QueryString["andTags"] != null)
				{
					double andTags = 0;
					if(Double.TryParse( Context.Request.QueryString["andTags"], System.Globalization.NumberStyles.Integer, null, out andTags ))
						this.AndTags = Convert.ToBoolean((int)andTags);
				}
			}

			base.ProcessFeed ();
		}
		protected override CachedFeed BuildFeed()
		{
			BaseRssWriter writer = null;
			DateTime date = DateTime.Now;

			FileGalleryThreadQuery query = new FileGalleryThreadQuery();
			query.CategoryID = CSContext.Current.CategoryID;
			query.PageSize = FileGalleryConfig.RssDefaultThreadsPerFeed;

			if(SortByDownloads)
				query.SortBy = EntriesSortBy.Downloads;
			else
				query.SortBy = EntriesSortBy.PostDate;

			if (this.Tags != null)
			{
				query.Tags = this.Tags;
				query.LogicallyOrTags = !this.AndTags;
			}
			
			query.SortOrder = SortOrder.Descending;
			query.SectionID = CurrentFolder.SectionID;

			ArrayList items = Entries.GetEntries(query).Threads;
            date =  items.Count > 0 ? ((Entry)items[0]).PostDate : DateTime.Now;

			if (this.Tags != null)
				writer = new FileGalleryTagRssWriter(items, CurrentFolder, this.BaseUrl, this.Tags);
			else
				writer = new FileGalleryRssWriter(items, CurrentFolder, this.BaseUrl);

			return new CachedFeed(date, null, writer.GetXml());

		}



	}
}
